<?php
namespace backend\modules\guild\controllers;

use backend\models\activeRecords\GuildBank;
use backend\models\activeRecords\GuildGame;
use backend\models\activeRecords\TGame;
use common\libs\Constants;
use common\models\User;
use mdm\admin\models\Assignment;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use backend\models\activeRecords\Guild;
use backend\modules\guild\models\GuildSearch;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * GuildController implements the CRUD actions for Guild model.
 */
class GuildController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Guild models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new GuildSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }

    /**
     * Displays a single Guild model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $params = Yii::$app->request->bodyParams;
        if(empty($params)){
            return $this->renderAjax('view', [
            'model' => $model,
            ]);
        }else{
            if($model->load($params) && $model->save()){
                return $this->redirect('index');
            }else{
                return $this->renderAjax('view', [
                    'model' => $model,
                ]);
            }
        }
    }

    /**
     * Creates a new Guild model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Guild();
        $model->add_time = time();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect('index');
        } else {
            return $this->renderAjax('create', ['model' => $model]);
        }
    }

    /**
     * Updates an existing Guild model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect('index');
        } else {
            return $this->renderAjax('update', ['model' => $model]);
        }
    }

    /**
     * Deletes an existing Guild model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

    /**
     * Finds the Guild model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Guild the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Guild::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
    * Asynchronous Validate Form Model
    */
    public function actionValidateForm ()
    {
        $model = new Guild();
        $model->load(Yii::$app->request->post());
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }

    public function actionBank($id)
    {
        $guildModel = $this->findModel($id);
        $model = GuildBank::findOne(['bank_guild'=>$guildModel->guild_sign]);
        $params = Yii::$app->request->bodyParams;
        if(empty($params)){
            $model = empty($model)?new GuildBank():$model;
            return $this->renderAjax('bank', ['model' => $model]);
        }else{
            if ($model->load(Yii::$app->request->post())){
                $model->bank_guild = $guildModel->guild_sign;
                if($model->save()) {
                    return $this->redirect('index');
                }
            } else {
                return $this->renderAjax('bank', ['model' => $model]);
            }
        }
    }

    public function actionGame($id)
    {
        $guildModel = $this->findModel($id);
        $model = GuildGame::findAll([
            'guild_sign'=>$guildModel->guild_sign,
            'is_delete'=>Constants::YesNo_No
        ]);
        $gameList = TGame::getGameListEliminate($model);
        return $this->renderAjax('game', ['guildModel'=>$guildModel,'model' => $model,'gameList'=>$gameList]);
    }

    public function actionCreateGuildMaster($id)
    {
        $guildModel = $this->findModel($id);
        $model = User::findOne($guildModel->user_id);
        $params = Yii::$app->request->bodyParams;
        if(empty($params)){
            $model = empty($model)?new User():$model;
            return $this->renderAjax('create-guild-master', ['model' => $model]);
        }else{
            if(empty($model)){
                $model = new User();
                $model->load($params);
                $model->setScenario('create');
                $model->parent = $guildModel->guild_sign;
                $model->real_name = $guildModel->guild_contact;
                $model->created_at = time();
                if($model->save()) {
                    $guildModel->user_id = $model->id;
                    $guildModel->save();
                    $roleGuildManager = Constants::ROLE_GUILD_MANAGER;
                    $assignModel = new Assignment($model->id);
                    $assignModel->assign([$roleGuildManager]);
                    return $this->redirect('index');
                }
            }elseif(!empty($model)&& $model->load($params)){
                $model->setScenario('update');
                $model->updated_at = time();
                if($model->save()) {
                    return $this->redirect('index');
                }
            }else {
                return $this->renderAjax('create-guild-master', ['model' => $model]);
            }
        }
    }

    public function actionInsertGameList()
    {
        $params = Yii::$app->request->bodyParams;
        $guildGame = new GuildGame();
        $result = $guildGame->insertGameList($params);
        echo $result;
    }

    public function actionRemoveGame()
    {
        $params = Yii::$app->request->bodyParams;
        $guildGame = new GuildGame();
        $result = $guildGame->removeGame($params);
        echo $result;
    }



}
